package com.laicunba.service.jzh.impl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.laicunba.service.jzh.JzhRemoteTransferBuService;
import com.laicunba.service.jzh.SecurityUtils;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.HttpUtil;
import com.laicunba.util.XmlUtil;

@Service
public class JzhRemoteTransferBuServiceImpl extends JzhBaseService implements JzhRemoteTransferBuService {
	private static final char SPLIT_CHAR = '|';

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Result post(Param param) {
		StringBuilder src = new StringBuilder();
		src.append(param.getCentAmt()).append(SPLIT_CHAR);
		src.append(param.getContractNo()).append(SPLIT_CHAR);
		src.append(param.getInCustNo()).append(SPLIT_CHAR);
		src.append(this.mchntCd).append(SPLIT_CHAR);
		src.append(param.getMchntTxnSsn()).append(SPLIT_CHAR);
		src.append(param.getOutCustNo()).append(SPLIT_CHAR);
		src.append(param.getRem()).append(SPLIT_CHAR);
		src.append("0.44");
		String signature = URLEncoder.encode(SecurityUtils.sign(src.toString()));
		Map map = new HashMap();
		map.put("ver", "0.44");
		map.put("mchnt_cd", this.mchntCd);
		map.put("mchnt_txn_ssn", param.getMchntTxnSsn());
		map.put("out_cust_no", param.getOutCustNo());
		map.put("in_cust_no", param.getInCustNo());
		map.put("amt", param.getCentAmt() + "");
		map.put("contract_no", param.getContractNo());
		map.put("rem", param.getRem());
		map.put("signature", signature);

		Result result = new Result();
		try {
			String xmlResult = HttpUtil.doPost(this.mchntURL + "/transferBu.action", map);
			System.out.println(xmlResult);
			Document doc = XmlUtil.parseXml(xmlResult.getBytes());
			result.setMchntCd(XmlUtil.getValue(doc, "mchnt_cd"));
			result.setRespCode(XmlUtil.getValue(doc, "resp_code"));
			result.setRespDesc(XmlUtil.getValue(doc, "resp_desc"));
			result.setMchntTxnSsn(XmlUtil.getValue(doc, "mchnt_txn_ssn"));
			result.setSignature(XmlUtil.getValue(doc, "signature"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String respSignSrc = String.format("<plain><resp_code>%s</resp_code><resp_desc>%s</resp_desc><mchnt_cd>%s</mchnt_cd><mchnt_txn_ssn>%s</mchnt_txn_ssn></plain>", result.getRespCode(),
				result.getRespDesc(), result.getMchntCd(), result.getMchntTxnSsn());
		AssertUtil.assertTrue(SecurityUtils.verifySign(respSignSrc, result.getSignature()), "VERIFY_SIGN_FAIL:校验签名错误");
		return result;
	}

}
